import { ImportExecl } from '@/utils/execl'
import { isArray, isObject } from 'lodash-es'
// @ts-ignore
import { dialog as Dialog } from '../Dialog.js'
import { message, Modal } from 'ant-design-vue'

import ImportExeclPreview from './ImportExeclPreview.vue'
import ImportErrors from './ImportErrors.vue'
import { BUSINESS_CODE } from '@/api/interceptors'

interface IImportExeclOptions {
  title: string;
  headers: number;
  hook?: (data: any, map: Record<string, string>) => void
}

export const ReadExecl = (fields: Record<string, string> = {}, options: IImportExeclOptions) => {
    return ImportExecl(fields, (options?.hook ? options.hook : (data, map) => {

      const division = options.headers

      if (division > 2) {
        throw new Error('当前导出不支持3级表头及以上表，请确认');
      }

      let tempFields: Record<string, string> = {}
      // let tempHeaders: Map<string, string> = new Map();

      // 提取表头
      for(let i = 0; i < division; i ++) {
        tempFields = {
          ...tempFields,
          ...(data[i] || {})
        }

        // for (let key in data[i]) {
        //   let header = tempHeaders.get(key)
        //   if (!header) {
        //     tempHeaders.set(key, data[i]);
        //   } else {
        //     // 二级表头
        //     header
        //   }
        // }
        
      } 

      for (const i in tempFields) {
        let value = tempFields[i];
        tempFields[value] = i;
        delete tempFields[i];
      }

      for (const i in fields) {
        const hasKey = tempFields[fields[i]]
        if (hasKey) {
          fields[i] = hasKey
        }
      }

      console.log('fields', fields, data)

      return {
        fields: fields,
        data: data.slice(division)
      }
    }))
    // .then((_) => {
    //   // @ts-ignore
    //   this.execlData = _.formatedData || []
    //   // @ts-ignore
    //   this.file = _.file
    // })
}

const generateColumns = (fields: Record<string, string> = {}) => {
  return Object.keys(fields).map(key => {
    return {
      title: fields[key],
      dataIndex: key,
      key
    }
  })
}

const formatFields = (fields: ITable.IColumn[]) => {
  let temp: Record<string, string> = {}
  // 展开多级表头
  fields.map(colnum => colnum.children || colnum).flat().forEach(field => {
    temp[field.key] = field.title || field.titleAlias
  })
  return temp;
}

export const handlerImport = async (fields: Record<string, string> | ITable.IColumn[], importApi: (...args: any[]) => Promise<unknown>, customOptions?: Partial<IImportExeclOptions>, extra?: Record<string, string>) => {
  let options: IImportExeclOptions = {
    headers: 1,
    title: ""
  }

  let TableColumns: ITable.IColumn[] = []

  if (customOptions && isObject(customOptions)) {
    options = {
      ...options,
      ...customOptions
    }
  }

  if (isArray(fields)) {
    TableColumns = fields.map(field => {
      return {
        ...field,
        // 兼容列表自定义表头模式
        title: field.title || field.titleAlias
      }
    })
    fields = formatFields(fields)
  }

  const {
    file,
    formatedData
  } = await ReadExecl({
    ...fields
  }, options)

  Dialog(
    ImportExeclPreview,
    {
      execlData: formatedData,
      execlColumns: TableColumns.length ? TableColumns : generateColumns(fields)
    },
    {
      title: options.title,
      centered: true,
      closable: false,
      width: "80%",
      on: {
        // @ts-ignore
        ok() {
          // @ts-ignore
          const data = this.$refs._component.execlData
          if (!data.length) {
            message.error('请导入数据')
            return false
          }
          return importApi({
            data,
            file_nam: file.name,
            ...(extra || {})
          })
          .then((_: any) => {
            const res = _.data
            if (res.code === BUSINESS_CODE.SUCCESS) {
              Modal.success({
                content: '数据导入成功',
                centered: true,
              })
              return true
            } else {
              if (typeof res.msg === 'string') {
                message.error({
                  content: res.msg
                })
              } else {
                Dialog(
                  ImportErrors,
                  {
                    messages: (res.msg as string[]).map((str) => ({ content: str })),
                  },
                  {
                    title: '异常数据列表',
                    width: '60%',
                    footer: null,
                  }
                )
              }
            }
          })
        }
      }
    }
  )
}